import random
from random import randint
import pandas as pd
import time
import datetime
from datetime import datetime
from datetime import timedelta
from math import *
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import  Process
from threading import Thread
import asyncio
from .models import Danmu
from .models import GoodsInfo
from .models import LiveRecord
from .models import OrderDetails
from .models import OrderInfo
from .models import ZbInfo
from .models import LiveroomInfo
from .models import SalesInfo
from django.db import connection
import asyncio

import pymysql


class live:
    def __init__(self,path,mod1,record,live_nu,host,start,end):
        self.mod1=mod1
        self.record=record# 直播记录号
        self.live_nu=live_nu#直播间号
        self.host=host#主播号
        self.start=datetime.strptime(start,'%Y-%m-%d %H:%M:%S')
        self.end=datetime.strptime(end,'%Y-%m-%d %H:%M:%S')
        df=pd.read_csv(path)
        self.danmu=list(df['弹幕数据'])
        self.guest=list(df['用户名'])
        ho=ZbInfo.objects.get(eid=host)
        live=LiveroomInfo.objects.get(liveroom_id=live_nu)
        LiveRecord.objects.create(live_record_id=record,liveroom=live,eid=ho,live_starttime=self.start,live_endtime=self.end)

    async def create_danmu(self):
        le=len(self.danmu)#记录弹幕数量，准备生成循环
        sign=0
        now=self.start
        sec=1
        self.dan=[]#生成一个记录列表，之后可以想想办法插入
        re = self.record
        while(now<self.end):#循环生成一个
            danzi={}#每行弹幕记录
            tim = (now + timedelta(seconds=sec)).strftime("%Y-%m-%d %H:%M:%S")
            id=self.record+str(sign).rjust(10, '0')
            ge=self.guest[sign]
            dn=self.danmu[sign]
            danzi['弹幕id']=id
            danzi['直播记录号']=re
            danzi['用户名称']=ge
            danzi['发送时间']=tim
            danzi['发送内容']=dn
            self.dan.append(danzi)
            await asyncio.sleep(sec)
            Danmu.objects.create(dm_id=id,live_record_id=re,user_name=ge,send_time=tim,send_text=dn)
            sec=randint(1,5)#弹幕发送的随机间隔
            sign=(sign+1)%le
            now= now + timedelta(seconds=sec)

    async def renshu(self):
        self.peo=[]
        self.peo_tim=[]
        renshu=1
        x=1#为了妥善的模拟人数变化，采用函数来表现趋势，2小时7200秒
        sec = 1
        now = self.start
        re = self.record
        while (now < self.end):  # 循环生成一个
            ren={}
            ren['人数']=renshu
            ren['时间']=now.strftime("%Y-%m-%d %H:%M:%S")
            self.mod1.objects.create(tim=ren['时间'],peo=renshu)
            await asyncio.sleep(sec)
            renshu=renshu+self._y(x)
            sec = 2  # 弹幕发送的随机间隔
            x=x+sec*20
            now = now + timedelta(seconds=sec)



    async def ding_dan(self):
        now = self.start
        N=randint(10,20)
        now = now + timedelta(seconds=N)
        m=1
        while (now < self.end):
            di={}
            di['订单编号']=self.record+str(m).rjust(7, '0')
            di['直播记录号']=self.record
            di['下单时间']=now.strftime("%Y-%m-%d %H:%M:%S")
            await asyncio.sleep(N)
            price = 0
            n = randint(1, 4)
            li = list(GoodsInfo.objects.all().values('goods_id', 'gprice'))
            #print(li)
            for i in range(n):  # 随机个商品
                #print(i)
                lens = len(li)
                #print(lens)
                item = li.pop(randint(0, lens - 1))
                #print(item)
                iid = item['goods_id']
                #print(iid)
                #print(item['gprice'])
                num = randint(1, 10)
                #print(num)
                price = price + num * int(item['gprice'])
                OrderDetails.objects.create(order_id=di['订单编号'],goods_id=iid,goods_num=num)
            gu=''.join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',10))
            #print(gu)
            #print(price)
            liiii=["SA42376","SA42377","SA42378","SA42379","SA42380","SA42381","SA42382","SA42383","SA42384","SA42385"]
            sta = ["未处理","未处理","未处理","未处理","未处理","退单"]
            xxx=random.choice(liiii)
            yyy = random.choice(sta)
            e=SalesInfo.objects.get(eid=xxx)
            OrderInfo.objects.create(order_id=di['订单编号'],live_record_id=self.record,cid=gu,eid=e,order_time=di['下单时间'],address="北京市",sum_price=price,process_status=yyy)
            #print("插入一条订单")
            N = randint(10, 30)
            m+=1
            now = now + timedelta(seconds=N)



    def _y(self,x):
        return ceil(random.uniform(0,1)*(5000-x)+randint(-500,300))#生成一个随机的y

    def main(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        future = asyncio.gather(self.create_danmu(), self.renshu(),self.ding_dan())
        loop.run_until_complete(future)






